Automatic EXIF update upon viewing
[lhc/web/wiklou.git] / includes / Image.php
1 <?php
2 /**
3 * @package MediaWiki
4 */
5
6 if ( $wgShowEXIF ) {
7 require_once ( 'exifReader.inc' ) ;
8 }
9
10 /**
11 * Class to represent an image
12 *
13 * Provides methods to retrieve paths (physical, logical, URL),
14 * to generate thumbnails or for uploading.
15 * @package MediaWiki
16 */
17 class Image
18 {
19 /**#@+
20 * @access private
21 */
22 var $name, # name of the image (constructor)
23 $imagePath, # Path of the image (loadFromXxx)
24 $url, # Image URL (accessor)
25 $title, # Title object for this image (constructor)
26 $fileExists, # does the image file exist on disk? (loadFromXxx)
27 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory (loadFromXxx)
28 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
29 $historyRes, # result of the query for the image's history (nextHistoryLine)
30 $width, # \
31 $height, # |
32 $bits, # --- returned by getimagesize (loadFromXxx)
33 $type, # |
34 $attr, # /
35 $size, # Size in bytes (loadFromXxx)
36 $exif, # EXIF data
37 $dataLoaded; # Whether or not all this has been loaded from the database (loadFromXxx)
38
39
40 /**#@-*/
41
42 /**
43 * Create an Image object from an image name
44 *
45 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
46 * @access public
47 */
48 function newFromName( $name ) {
49 $title = Title::makeTitleSafe( NS_IMAGE, $name );
50 return new Image( $title );
51 }
52
53 /**
54 * Obsolete factory function, use constructor
55 */
56 function newFromTitle( $title ) {
57 return new Image( $title );
58 }
59
60 function Image( $title ) {
61 $this->title =& $title;
62 $this->name = $title->getDBkey();
63 $this->exif = serialize ( array() ) ;
64
65 $n = strrpos( $this->name, '.' );
66 $this->extension = strtolower( $n ? substr( $this->name, $n + 1 ) : '' );
67 $this->historyLine = 0;
68
69 $this->dataLoaded = false;
70 }
71
72 /**
73 * Get the memcached keys
74 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
75 */
76 function getCacheKeys( $shared = false ) {
77 global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
78
79 $foundCached = false;
80 $hashedName = md5($this->name);
81 $keys = array( "$wgDBname:Image:$hashedName" );
82 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
83 $keys[] = "$wgSharedUploadDBname:Image:$hashedName";
84 }
85 return $keys;
86 }
87
88 /**
89 * Try to load image metadata from memcached. Returns true on success.
90 */
91 function loadFromCache() {
92 global $wgUseSharedUploads, $wgMemc;
93 $fname = 'Image::loadFromMemcached';
94 wfProfileIn( $fname );
95 $this->dataLoaded = false;
96 $keys = $this->getCacheKeys();
97 $cachedValues = $wgMemc->get( $keys[0] );
98
99 // Check if the key existed and belongs to this version of MediaWiki
100 if (!empty($cachedValues) && is_array($cachedValues) && isset($cachedValues['width']) && $cachedValues['fileExists']) {
101 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
102 # if this is shared file, we need to check if image
103 # in shared repository has not changed
104 if ( isset( $keys[1] ) ) {
105 $commonsCachedValues = $wgMemc->get( $keys[1] );
106 if (!empty($commonsCachedValues) && is_array($commonsCachedValues) && isset($commonsCachedValues['width'])) {
107 $this->name = $commonsCachedValues['name'];
108 $this->imagePath = $commonsCachedValues['imagePath'];
109 $this->fileExists = $commonsCachedValues['fileExists'];
110 $this->width = $commonsCachedValues['width'];
111 $this->height = $commonsCachedValues['height'];
112 $this->bits = $commonsCachedValues['bits'];
113 $this->type = $commonsCachedValues['type'];
114 $this->exif = $commonsCachedValues['exif'];
115 $this->size = $commonsCachedValues['size'];
116 $this->fromSharedDirectory = true;
117 $this->dataLoaded = true;
118 $this->imagePath = $this->getFullPath(true);
119 }
120 }
121 }
122 else {
123 $this->name = $cachedValues['name'];
124 $this->imagePath = $cachedValues['imagePath'];
125 $this->fileExists = $cachedValues['fileExists'];
126 $this->width = $cachedValues['width'];
127 $this->height = $cachedValues['height'];
128 $this->bits = $cachedValues['bits'];
129 $this->type = $cachedValues['type'];
130 $this->exif = $cachedValues['exif'];
131 $this->size = $cachedValues['size'];
132 $this->fromSharedDirectory = false;
133 $this->dataLoaded = true;
134 $this->imagePath = $this->getFullPath();
135 }
136 }
137
138 wfProfileOut( $fname );
139 return $this->dataLoaded;
140 }
141
142 /**
143 * Save the image metadata to memcached
144 */
145 function saveToCache() {
146 global $wgMemc;
147 $this->load();
148 // We can't cache metadata for non-existent files, because if the file later appears
149 // in commons, the local keys won't be purged.
150 if ( $this->fileExists ) {
151 $keys = $this->getCacheKeys();
152
153 $cachedValues = array('name' => $this->name,
154 'imagePath' => $this->imagePath,
155 'fileExists' => $this->fileExists,
156 'fromShared' => $this->fromSharedDirectory,
157 'width' => $this->width,
158 'height' => $this->height,
159 'bits' => $this->bits,
160 'type' => $this->type,
161 'exif' => $this->exif,
162 'size' => $this->size);
163
164 $wgMemc->set( $keys[0], $cachedValues );
165 }
166 }
167
168 /**
169 * Load metadata from the file itself
170 */
171 function loadFromFile() {
172 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgLang;
173 $fname = 'Image::loadFromFile';
174 wfProfileIn( $fname );
175 $this->imagePath = $this->getFullPath();
176 $this->fileExists = file_exists( $this->imagePath );
177 $this->fromSharedDirectory = false;
178 $gis = false;
179
180 # If the file is not found, and a shared upload directory is used, look for it there.
181 if (!$this->fileExists && $wgUseSharedUploads && $wgSharedUploadDirectory) {
182 # In case we're on a wgCapitalLinks=false wiki, we
183 # capitalize the first letter of the filename before
184 # looking it up in the shared repository.
185 $sharedImage = Image::newFromName( $wgLang->ucfirst($this->name) );
186 $this->fileExists = file_exists( $sharedImage->getFullPath(true) );
187 if ( $this->fileExists ) {
188 $this->name = $sharedImage->name;
189 $this->imagePath = $this->getFullPath(true);
190 $this->fromSharedDirectory = true;
191 }
192 }
193
194 if ( $this->fileExists ) {
195 # Get size in bytes
196 $this->size = filesize( $this->imagePath );
197
198 # Height and width
199 # Don't try to get the width and height of sound and video files, that's bad for performance
200 if ( !Image::isKnownImageExtension( $this->extension ) ) {
201 $gis = false;
202 } elseif( $this->extension == 'svg' ) {
203 wfSuppressWarnings();
204 $gis = wfGetSVGsize( $this->imagePath );
205 wfRestoreWarnings();
206 } else {
207 wfSuppressWarnings();
208 $gis = getimagesize( $this->imagePath );
209 wfRestoreWarnings();
210 }
211 }
212 if( $gis === false ) {
213 $this->width = 0;
214 $this->height = 0;
215 $this->bits = 0;
216 $this->type = 0;
217 $this->exif = serialize ( array() ) ;
218 } else {
219 $this->width = $gis[0];
220 $this->height = $gis[1];
221 $this->type = $gis[2];
222 $this->exif = serialize ( $this->retrieveExifData() ) ;
223 if ( isset( $gis['bits'] ) ) {
224 $this->bits = $gis['bits'];
225 } else {
226 $this->bits = 0;
227 }
228 }
229 $this->dataLoaded = true;
230 wfProfileOut( $fname );
231 }
232
233 /**
234 * Load image metadata from the DB
235 */
236 function loadFromDB() {
237 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgLang;
238 $fname = 'Image::loadFromDB';
239 wfProfileIn( $fname );
240
241 $dbr =& wfGetDB( DB_SLAVE );
242 $row = $dbr->selectRow( 'image',
243 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' , 'img_exif' ),
244 array( 'img_name' => $this->name ), $fname );
245 if ( $row ) {
246 $this->fromSharedDirectory = false;
247 $this->fileExists = true;
248 $this->loadFromRow( $row );
249 $this->imagePath = $this->getFullPath();
250 // Check for rows from a previous schema, quietly upgrade them
251 if ( $this->type == -1 ) {
252 $this->upgradeRow();
253 }
254 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
255 # In case we're on a wgCapitalLinks=false wiki, we
256 # capitalize the first letter of the filename before
257 # looking it up in the shared repository.
258 $name = $wgLang->ucfirst($this->name);
259
260 $row = $dbr->selectRow( "`$wgSharedUploadDBname`.image",
261 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' ),
262 array( 'img_name' => $name ), $fname );
263 if ( $row ) {
264 $this->fromSharedDirectory = true;
265 $this->fileExists = true;
266 $this->imagePath = $this->getFullPath(true);
267 $this->name = $name;
268 $this->loadFromRow( $row );
269
270 // Check for rows from a previous schema, quietly upgrade them
271 if ( $this->type == -1 ) {
272 $this->upgradeRow();
273 }
274 }
275 }
276
277 if ( !$row ) {
278 $this->size = 0;
279 $this->width = 0;
280 $this->height = 0;
281 $this->bits = 0;
282 $this->type = 0;
283 $this->fileExists = false;
284 $this->fromSharedDirectory = false;
285 $this->exif = serialize ( array() ) ;
286 }
287
288 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
289 $this->dataLoaded = true;
290 }
291
292 /*
293 * Load image metadata from a DB result row
294 */
295 function loadFromRow( &$row ) {
296 $this->size = $row->img_size;
297 $this->width = $row->img_width;
298 $this->height = $row->img_height;
299 $this->bits = $row->img_bits;
300 $this->type = $row->img_type;
301 $this->exif = $row->img_exif;
302 if ( $this->exif == "" ) $this->exif = serialize ( array() ) ;
303 $this->dataLoaded = true;
304 }
305
306 /**
307 * Load image metadata from cache or DB, unless already loaded
308 */
309 function load() {
310 global $wgSharedUploadDBname, $wgUseSharedUploads;
311 if ( !$this->dataLoaded ) {
312 if ( !$this->loadFromCache() ) {
313 $this->loadFromDB();
314 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
315 $this->loadFromFile();
316 } elseif ( $this->fileExists ) {
317 $this->saveToCache();
318 }
319 }
320 $this->dataLoaded = true;
321 }
322 }
323
324 /**
325 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
326 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
327 */
328 function upgradeRow() {
329 global $wgDBname, $wgSharedUploadDBname;
330 $fname = 'Image::upgradeRow';
331 $this->loadFromFile();
332 $dbw =& wfGetDB( DB_MASTER );
333
334 if ( $this->fromSharedDirectory ) {
335 if ( !$wgSharedUploadDBname ) {
336 return;
337 }
338
339 // Write to the other DB using selectDB, not database selectors
340 // This avoids breaking replication in MySQL
341 $dbw->selectDB( $wgSharedUploadDBname );
342 }
343 $dbw->update( '`image`',
344 array(
345 'img_width' => $this->width,
346 'img_height' => $this->height,
347 'img_bits' => $this->bits,
348 'img_type' => $this->type,
349 'img_exif' => $this->exif,
350 ), array( 'img_name' => $this->name ), $fname
351 );
352 if ( $this->fromSharedDirectory ) {
353 $dbw->selectDB( $wgDBname );
354 }
355 }
356
357 /**
358 * Return the name of this image
359 * @access public
360 */
361 function getName() {
362 return $this->name;
363 }
364
365 /**
366 * Return the associated title object
367 * @access public
368 */
369 function getTitle() {
370 return $this->title;
371 }
372
373 /**
374 * Return the URL of the image file
375 * @access public
376 */
377 function getURL() {
378 if ( !$this->url ) {
379 $this->load();
380 if($this->fileExists) {
381 $this->url = Image::imageUrl( $this->name, $this->fromSharedDirectory );
382 } else {
383 $this->url = '';
384 }
385 }
386 return $this->url;
387 }
388
389 function getViewURL() {
390 if( $this->mustRender() ) {
391 return $this->createThumb( $this->getWidth() );
392 } else {
393 return $this->getURL();
394 }
395 }
396
397 /**
398 * Return the image path of the image in the
399 * local file system as an absolute path
400 * @access public
401 */
402 function getImagePath() {
403 $this->load();
404 return $this->imagePath;
405 }
406
407 /**
408 * Return the width of the image
409 *
410 * Returns -1 if the file specified is not a known image type
411 * @access public
412 */
413 function getWidth() {
414 $this->load();
415 return $this->width;
416 }
417
418 /**
419 * Return the height of the image
420 *
421 * Returns -1 if the file specified is not a known image type
422 * @access public
423 */
424 function getHeight() {
425 $this->load();
426 return $this->height;
427 }
428
429 /**
430 * Return the size of the image file, in bytes
431 * @access public
432 */
433 function getSize() {
434 $this->load();
435 return $this->size;
436 }
437
438 /**
439 * Return the type of the image
440 *
441 * - 1 GIF
442 * - 2 JPG
443 * - 3 PNG
444 * - 15 WBMP
445 * - 16 XBM
446 */
447 function getType() {
448 $this->load();
449 return $this->type;
450 }
451
452 /**
453 * Return the escapeLocalURL of this image
454 * @access public
455 */
456 function getEscapeLocalURL() {
457 $this->getTitle();
458 return $this->title->escapeLocalURL();
459 }
460
461 /**
462 * Return the escapeFullURL of this image
463 * @access public
464 */
465 function getEscapeFullURL() {
466 $this->getTitle();
467 return $this->title->escapeFullURL();
468 }
469
470 /**
471 * Return the URL of an image, provided its name.
472 *
473 * @param string $name Name of the image, without the leading "Image:"
474 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
475 * @access public
476 * @static
477 */
478 function imageUrl( $name, $fromSharedDirectory = false ) {
479 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
480 if($fromSharedDirectory) {
481 $base = '';
482 $path = $wgSharedUploadPath;
483 } else {
484 $base = $wgUploadBaseUrl;
485 $path = $wgUploadPath;
486 }
487 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
488 return wfUrlencode( $url );
489 }
490
491 /**
492 * Returns true if the image file exists on disk.
493 *
494 * @access public
495 */
496 function exists() {
497 $this->load();
498 return $this->fileExists;
499 }
500
501 /**
502 *
503 * @access private
504 */
505 function thumbUrl( $width, $subdir='thumb') {
506 global $wgUploadPath, $wgUploadBaseUrl,
507 $wgSharedUploadPath,$wgSharedUploadDirectory,
508 $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
509
510 // Generate thumb.php URL if possible
511 $script = false;
512 $url = false;
513
514 if ( $this->fromSharedDirectory ) {
515 if ( $wgSharedThumbnailScriptPath ) {
516 $script = $wgSharedThumbnailScriptPath;
517 }
518 } else {
519 if ( $wgThumbnailScriptPath ) {
520 $script = $wgThumbnailScriptPath;
521 }
522 }
523 if ( $script ) {
524 $url = $script . '?f=' . urlencode( $this->name ) . '&w=' . urlencode( $width );
525 } else {
526 $name = $this->thumbName( $width );
527 if($this->fromSharedDirectory) {
528 $base = '';
529 $path = $wgSharedUploadPath;
530 } else {
531 $base = $wgUploadBaseUrl;
532 $path = $wgUploadPath;
533 }
534 if ( Image::isHashed( $this->fromSharedDirectory ) ) {
535 $url = "{$base}{$path}/{$subdir}" .
536 wfGetHashPath($this->name, $this->fromSharedDirectory)
537 . $this->name.'/'.$name;
538 $url = wfUrlencode( $url );
539 } else {
540 $url = "{$base}{$path}/{$subdir}/{$name}";
541 }
542 }
543 return array( $script !== false, $url );
544 }
545
546 /**
547 * Return the file name of a thumbnail of the specified width
548 *
549 * @param integer $width Width of the thumbnail image
550 * @param boolean $shared Does the thumbnail come from the shared repository?
551 * @access private
552 */
553 function thumbName( $width ) {
554 $thumb = $width."px-".$this->name;
555 if( $this->extension == 'svg' ) {
556 # Rasterize SVG vector images to PNG
557 $thumb .= '.png';
558 }
559 return $thumb;
560 }
561
562 /**
563 * Create a thumbnail of the image having the specified width/height.
564 * The thumbnail will not be created if the width is larger than the
565 * image's width. Let the browser do the scaling in this case.
566 * The thumbnail is stored on disk and is only computed if the thumbnail
567 * file does not exist OR if it is older than the image.
568 * Returns the URL.
569 *
570 * Keeps aspect ratio of original image. If both width and height are
571 * specified, the generated image will be no bigger than width x height,
572 * and will also have correct aspect ratio.
573 *
574 * @param integer $width maximum width of the generated thumbnail
575 * @param integer $height maximum height of the image (optional)
576 * @access public
577 */
578 function createThumb( $width, $height=-1 ) {
579 $thumb = $this->getThumbnail( $width, $height );
580 if( is_null( $thumb ) ) return '';
581 return $thumb->getUrl();
582 }
583
584 /**
585 * As createThumb, but returns a ThumbnailImage object. This can
586 * provide access to the actual file, the real size of the thumb,
587 * and can produce a convenient <img> tag for you.
588 *
589 * @param integer $width maximum width of the generated thumbnail
590 * @param integer $height maximum height of the image (optional)
591 * @return ThumbnailImage
592 * @access public
593 */
594 function &getThumbnail( $width, $height=-1 ) {
595 if ( $height == -1 ) {
596 return $this->renderThumb( $width );
597 }
598 $this->load();
599 if ( $width < $this->width ) {
600 $thumbheight = $this->height * $width / $this->width;
601 $thumbwidth = $width;
602 } else {
603 $thumbheight = $this->height;
604 $thumbwidth = $this->width;
605 }
606 if ( $thumbheight > $height ) {
607 $thumbwidth = $thumbwidth * $height / $thumbheight;
608 $thumbheight = $height;
609 }
610 $thumb = $this->renderThumb( $thumbwidth );
611 if( is_null( $thumb ) ) {
612 $thumb = $this->iconThumb();
613 }
614 return $thumb;
615 }
616
617 /**
618 * @return ThumbnailImage
619 */
620 function iconThumb() {
621 global $wgStylePath, $wgStyleDirectory;
622
623 $try = array( 'fileicon-' . $this->extension . '.png', 'fileicon.png' );
624 foreach( $try as $icon ) {
625 $path = '/common/images/' . $icon;
626 $filepath = $wgStyleDirectory . $path;
627 if( file_exists( $filepath ) ) {
628 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
629 }
630 }
631 return null;
632 }
633
634 /**
635 * Create a thumbnail of the image having the specified width.
636 * The thumbnail will not be created if the width is larger than the
637 * image's width. Let the browser do the scaling in this case.
638 * The thumbnail is stored on disk and is only computed if the thumbnail
639 * file does not exist OR if it is older than the image.
640 * Returns an object which can return the pathname, URL, and physical
641 * pixel size of the thumbnail -- or null on failure.
642 *
643 * @return ThumbnailImage
644 * @access private
645 */
646 function /* private */ renderThumb( $width, $useScript = true ) {
647 global $wgUseSquid, $wgInternalServer;
648 global $wgThumbnailScriptPath, $wgSharedThumbnailScriptPath;
649
650 $width = IntVal( $width );
651
652 $this->load();
653 if ( ! $this->exists() )
654 {
655 # If there is no image, there will be no thumbnail
656 return null;
657 }
658
659 # Sanity check $width
660 if( $width <= 0 ) {
661 # BZZZT
662 return null;
663 }
664
665 if( $width > $this->width && !$this->mustRender() ) {
666 # Don't make an image bigger than the source
667 return new ThumbnailImage( $this->getViewURL(), $this->getWidth(), $this->getHeight() );
668 }
669
670 $height = floor( $this->height * ( $width/$this->width ) );
671
672 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
673 if ( $isScriptUrl && $useScript ) {
674 // Use thumb.php to render the image
675 return new ThumbnailImage( $url, $width, $height );
676 }
677
678 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory );
679 $thumbPath = wfImageThumbDir( $this->name, $this->fromSharedDirectory ).'/'.$thumbName;
680
681 if ( !file_exists( $thumbPath ) ) {
682 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory ).
683 '/'.$thumbName;
684 $done = false;
685 if ( file_exists( $oldThumbPath ) ) {
686 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath) ) {
687 rename( $oldThumbPath, $thumbPath );
688 $done = true;
689 } else {
690 unlink( $oldThumbPath );
691 }
692 }
693 if ( !$done ) {
694 $this->reallyRenderThumb( $thumbPath, $width, $height );
695
696 # Purge squid
697 # This has to be done after the image is updated and present for all machines on NFS,
698 # or else the old version might be stored into the squid again
699 if ( $wgUseSquid ) {
700 if ( substr( $url, 0, 4 ) == 'http' ) {
701 $urlArr = array( $url );
702 } else {
703 $urlArr = array( $wgInternalServer.$url );
704 }
705 wfPurgeSquidServers($urlArr);
706 }
707 }
708 }
709 return new ThumbnailImage( $url, $width, $height, $thumbPath );
710 } // END OF function renderThumb
711
712 /**
713 * Really render a thumbnail
714 *
715 * @access private
716 */
717 function /*private*/ reallyRenderThumb( $thumbPath, $width, $height ) {
718 global $wgSVGConverters, $wgSVGConverter,
719 $wgUseImageMagick, $wgImageMagickConvertCommand;
720
721 $this->load();
722
723 if( $this->extension == 'svg' ) {
724 global $wgSVGConverters, $wgSVGConverter;
725 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
726 global $wgSVGConverterPath;
727 $cmd = str_replace(
728 array( '$path/', '$width', '$input', '$output' ),
729 array( $wgSVGConverterPath,
730 $width,
731 escapeshellarg( $this->imagePath ),
732 escapeshellarg( $thumbPath ) ),
733 $wgSVGConverters[$wgSVGConverter] );
734 $conv = shell_exec( $cmd );
735 } else {
736 $conv = false;
737 }
738 } elseif ( $wgUseImageMagick ) {
739 # use ImageMagick
740 # Specify white background color, will be used for transparent images
741 # in Internet Explorer/Windows instead of default black.
742 $cmd = $wgImageMagickConvertCommand .
743 " -quality 85 -background white -geometry {$width} ".
744 escapeshellarg($this->imagePath) . " " .
745 escapeshellarg($thumbPath);
746 $conv = shell_exec( $cmd );
747 } else {
748 # Use PHP's builtin GD library functions.
749 #
750 # First find out what kind of file this is, and select the correct
751 # input routine for this.
752
753 $truecolor = false;
754
755 switch( $this->type ) {
756 case 1: # GIF
757 $src_image = imagecreatefromgif( $this->imagePath );
758 break;
759 case 2: # JPG
760 $src_image = imagecreatefromjpeg( $this->imagePath );
761 $truecolor = true;
762 break;
763 case 3: # PNG
764 $src_image = imagecreatefrompng( $this->imagePath );
765 $truecolor = ( $this->bits > 8 );
766 break;
767 case 15: # WBMP for WML
768 $src_image = imagecreatefromwbmp( $this->imagePath );
769 break;
770 case 16: # XBM
771 $src_image = imagecreatefromxbm( $this->imagePath );
772 break;
773 default:
774 return 'Image type not supported';
775 break;
776 }
777 if ( $truecolor ) {
778 $dst_image = imagecreatetruecolor( $width, $height );
779 } else {
780 $dst_image = imagecreate( $width, $height );
781 }
782 imagecopyresampled( $dst_image, $src_image,
783 0,0,0,0,
784 $width, $height, $this->width, $this->height );
785 switch( $this->type ) {
786 case 1: # GIF
787 case 3: # PNG
788 case 15: # WBMP
789 case 16: # XBM
790 imagepng( $dst_image, $thumbPath );
791 break;
792 case 2: # JPEG
793 imageinterlace( $dst_image );
794 imagejpeg( $dst_image, $thumbPath, 95 );
795 break;
796 default:
797 break;
798 }
799 imagedestroy( $dst_image );
800 imagedestroy( $src_image );
801 }
802 #
803 # Check for zero-sized thumbnails. Those can be generated when
804 # no disk space is available or some other error occurs
805 #
806 if( file_exists( $thumbPath ) ) {
807 $thumbstat = stat( $thumbPath );
808 if( $thumbstat['size'] == 0 ) {
809 unlink( $thumbPath );
810 }
811 }
812 }
813
814 /**
815 * Get all thumbnail names previously generated for this image
816 */
817 function getThumbnails( $shared = false ) {
818 if ( Image::isHashed( $shared ) ) {
819 $this->load();
820 $files = array();
821 $dir = wfImageThumbDir( $this->name, $shared );
822
823 // This generates an error on failure, hence the @
824 $handle = @opendir( $dir );
825
826 if ( $handle ) {
827 while ( false !== ( $file = readdir($handle) ) ) {
828 if ( $file{0} != '.' ) {
829 $files[] = $file;
830 }
831 }
832 closedir( $handle );
833 }
834 } else {
835 $files = array();
836 }
837
838 return $files;
839 }
840
841 /**
842 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
843 */
844 function purgeCache( $archiveFiles = array(), $shared = false ) {
845 global $wgInternalServer, $wgUseSquid;
846
847 // Refresh metadata cache
848 clearstatcache();
849 $this->loadFromFile();
850 $this->saveToCache();
851
852 // Delete thumbnails
853 $files = $this->getThumbnails( $shared );
854 $dir = wfImageThumbDir( $this->name, $shared );
855 $urls = array();
856 foreach ( $files as $file ) {
857 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
858 $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory );
859 @unlink( "$dir/$file" );
860 }
861 }
862
863 // Purge the squid
864 if ( $wgUseSquid ) {
865 $urls[] = $wgInternalServer . $this->getViewURL();
866 foreach ( $archiveFiles as $file ) {
867 $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
868 }
869 wfPurgeSquidServers( $urls );
870 }
871 }
872
873 /**
874 * Return the image history of this image, line by line.
875 * starts with current version, then old versions.
876 * uses $this->historyLine to check which line to return:
877 * 0 return line for current version
878 * 1 query for old versions, return first one
879 * 2, ... return next old version from above query
880 *
881 * @access public
882 */
883 function nextHistoryLine() {
884 $fname = 'Image::nextHistoryLine()';
885 $dbr =& wfGetDB( DB_SLAVE );
886 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
887 $this->historyRes = $dbr->select( 'image',
888 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
889 array( 'img_name' => $this->title->getDBkey() ),
890 $fname
891 );
892 if ( 0 == wfNumRows( $this->historyRes ) ) {
893 return FALSE;
894 }
895 } else if ( $this->historyLine == 1 ) {
896 $this->historyRes = $dbr->select( 'oldimage',
897 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
898 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
899 ), array( 'oi_name' => $this->title->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
900 );
901 }
902 $this->historyLine ++;
903
904 return $dbr->fetchObject( $this->historyRes );
905 }
906
907 /**
908 * Reset the history pointer to the first element of the history
909 * @access public
910 */
911 function resetHistory() {
912 $this->historyLine = 0;
913 }
914
915 /**
916 * Return true if the file is of a type that can't be directly
917 * rendered by typical browsers and needs to be re-rasterized.
918 * @return bool
919 */
920 function mustRender() {
921 $this->load();
922 return ( $this->extension == 'svg' );
923 }
924
925 /**
926 * Return the full filesystem path to the file. Note that this does
927 * not mean that a file actually exists under that location.
928 *
929 * This path depends on whether directory hashing is active or not,
930 * i.e. whether the images are all found in the same directory,
931 * or in hashed paths like /images/3/3c.
932 *
933 * @access public
934 * @param boolean $fromSharedDirectory Return the path to the file
935 * in a shared repository (see $wgUseSharedRepository and related
936 * options in DefaultSettings.php) instead of a local one.
937 *
938 */
939 function getFullPath( $fromSharedRepository = false ) {
940 global $wgUploadDirectory, $wgSharedUploadDirectory;
941 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
942
943 $dir = $fromSharedRepository ? $wgSharedUploadDirectory :
944 $wgUploadDirectory;
945
946 // $wgSharedUploadDirectory may be false, if thumb.php is used
947 if ( $dir ) {
948 $fullpath = $dir . wfGetHashPath($this->name, $fromSharedRepository) . $this->name;
949 } else {
950 $fullpath = false;
951 }
952
953 return $fullpath;
954 }
955
956 /**
957 * @return bool
958 * @static
959 */
960 function isHashed( $shared ) {
961 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
962 return $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
963 }
964
965 /**
966 * @return bool
967 * @static
968 */
969 function isKnownImageExtension( $ext ) {
970 static $extensions = array( 'svg', 'png', 'jpg', 'jpeg', 'gif', 'bmp', 'xbm' );
971 return in_array( $ext, $extensions );
972 }
973
974 /**
975 * Record an image upload in the upload log and the image table
976 */
977 function recordUpload( $oldver, $desc, $copyStatus = '', $source = '' ) {
978 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
979 global $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
980
981 $fname = 'Image::recordUpload';
982 $dbw =& wfGetDB( DB_MASTER );
983
984 # img_name must be unique
985 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
986 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
987 }
988
989 // Delete thumbnails and refresh the metadata cache
990 $this->purgeCache();
991
992 // Fail now if the image isn't there
993 if ( !$this->fileExists || $this->fromSharedDirectory ) {
994 return false;
995 }
996
997 if ( $wgUseCopyrightUpload ) {
998 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
999 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1000 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
1001 } else {
1002 $textdesc = $desc;
1003 }
1004
1005 $now = $dbw->timestamp();
1006
1007 # Test to see if the row exists using INSERT IGNORE
1008 # This avoids race conditions by locking the row until the commit, and also
1009 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1010 $dbw->insert( 'image',
1011 array(
1012 'img_name' => $this->name,
1013 'img_size'=> $this->size,
1014 'img_width' => $this->width,
1015 'img_height' => $this->height,
1016 'img_bits' => $this->bits,
1017 'img_type' => $this->type,
1018 'img_timestamp' => $now,
1019 'img_description' => $desc,
1020 'img_user' => $wgUser->getID(),
1021 'img_user_text' => $wgUser->getName(),
1022 'img_exif' => $this->exif,
1023 ), $fname, 'IGNORE'
1024 );
1025 $descTitle = $this->getTitle();
1026 $purgeURLs = array();
1027
1028 if ( $dbw->affectedRows() ) {
1029 # Successfully inserted, this is a new image
1030 $id = $descTitle->getArticleID();
1031
1032 if ( $id == 0 ) {
1033 $article = new Article( $descTitle );
1034 $article->insertNewArticle( $textdesc, $desc, false, false, true );
1035 }
1036 } else {
1037 # Collision, this is an update of an image
1038 # Insert previous contents into oldimage
1039 $dbw->insertSelect( 'oldimage', 'image',
1040 array(
1041 'oi_name' => 'img_name',
1042 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1043 'oi_size' => 'img_size',
1044 'oi_width' => 'img_width',
1045 'oi_height' => 'img_height',
1046 'oi_bits' => 'img_bits',
1047 'oi_type' => 'img_type',
1048 'oi_timestamp' => 'img_timestamp',
1049 'oi_description' => 'img_description',
1050 'oi_user' => 'img_user',
1051 'oi_user_text' => 'img_user_text',
1052 ), array( 'img_name' => $this->name ), $fname
1053 );
1054
1055 # Update the current image row
1056 $dbw->update( 'image',
1057 array( /* SET */
1058 'img_size' => $this->size,
1059 'img_width' => $this->width,
1060 'img_height' => $this->height,
1061 'img_bits' => $this->bits,
1062 'img_type' => $this->type,
1063 'img_timestamp' => $now,
1064 'img_user' => $wgUser->getID(),
1065 'img_user_text' => $wgUser->getName(),
1066 'img_description' => $desc,
1067 'img_exif' => $this->exif,
1068 ), array( /* WHERE */
1069 'img_name' => $this->name
1070 ), $fname
1071 );
1072
1073 # Invalidate the cache for the description page
1074 $descTitle->invalidateCache();
1075 $purgeURLs[] = $descTitle->getInternalURL();
1076 }
1077
1078 # Invalidate cache for all pages using this image
1079 $linksTo = $this->getLinksTo();
1080
1081 if ( $wgUseSquid ) {
1082 $u = SquidUpdate::newFromTitles( $linksTo, $purgeURLs );
1083 array_push( $wgPostCommitUpdateList, $u );
1084 }
1085 Title::touchArray( $linksTo );
1086
1087 $log = new LogPage( 'upload' );
1088 $log->addEntry( 'upload', $descTitle, $desc );
1089
1090 return true;
1091 }
1092
1093 /**
1094 * Get an array of Title objects which are articles which use this image
1095 * Also adds their IDs to the link cache
1096 *
1097 * This is mostly copied from Title::getLinksTo()
1098 */
1099 function getLinksTo( $options = '' ) {
1100 global $wgLinkCache;
1101 $fname = 'Image::getLinksTo';
1102 wfProfileIn( $fname );
1103
1104 if ( $options ) {
1105 $db =& wfGetDB( DB_MASTER );
1106 } else {
1107 $db =& wfGetDB( DB_SLAVE );
1108 }
1109
1110 extract( $db->tableNames( 'page', 'imagelinks' ) );
1111 $encName = $db->addQuotes( $this->name );
1112 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1113 $res = $db->query( $sql, $fname );
1114
1115 $retVal = array();
1116 if ( $db->numRows( $res ) ) {
1117 while ( $row = $db->fetchObject( $res ) ) {
1118 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1119 $wgLinkCache->addGoodLink( $row->page_id, $titleObj->getPrefixedDBkey() );
1120 $retVal[] = $titleObj;
1121 }
1122 }
1123 }
1124 $db->freeResult( $res );
1125 return $retVal;
1126 }
1127
1128 function retrieveExifData () {
1129 global $wgShowEXIF ;
1130 if ( ! $wgShowEXIF ) return array () ;
1131
1132 $file = $this->imagePath ;
1133 $per = new phpExifReader ( $file ) ;
1134 $per->processFile () ;
1135 $a = $per->getImageInfo() ;
1136 unset ( $a["FileName"] ) ;
1137 unset ( $a["Thumbnail"] ) ;
1138 return $a ;
1139 }
1140
1141 function getExifData () {
1142 global $wgShowEXIF ;
1143 if ( ! $wgShowEXIF ) return array () ;
1144
1145 $ret = unserialize ( $this->exif ) ;
1146 if ( count ( $ret ) == 0 ) { # No EXIF data was stored for this image
1147 $this->updateExifData() ;
1148 $ret = unserialize ( $this->exif ) ;
1149 }
1150
1151 return $ret ;
1152 }
1153
1154 function updateExifData () {
1155 global $wgShowEXIF ;
1156 if ( ! $wgShowEXIF ) return ;
1157 if ( false === $this->getImagePath() ) return ; # Not a local image
1158
1159 $fname = "Image:updateExifData" ;
1160
1161 # Get EXIF data from image
1162 $exif = $this->retrieveExifData () ;
1163 $this->exif = serialize ( $exif ) ;
1164
1165 # Update EXIF data in database
1166 $dbw =& wfGetDB( DB_MASTER );
1167 $dbw->update( '`image`',
1168 array( 'img_exif' => $this->exif ),
1169 array( 'img_name' => $this->name ),
1170 $fname
1171 );
1172 }
1173
1174
1175 } //class
1176
1177
1178 /**
1179 * Returns the image directory of an image
1180 * If the directory does not exist, it is created.
1181 * The result is an absolute path.
1182 *
1183 * This function is called from thumb.php before Setup.php is included
1184 *
1185 * @param string $fname file name of the image file
1186 * @access public
1187 */
1188 function wfImageDir( $fname ) {
1189 global $wgUploadDirectory, $wgHashedUploadDirectory;
1190
1191 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1192
1193 $hash = md5( $fname );
1194 $oldumask = umask(0);
1195 $dest = $wgUploadDirectory . '/' . $hash{0};
1196 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1197 $dest .= '/' . substr( $hash, 0, 2 );
1198 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1199
1200 umask( $oldumask );
1201 return $dest;
1202 }
1203
1204 /**
1205 * Returns the image directory of an image's thubnail
1206 * If the directory does not exist, it is created.
1207 * The result is an absolute path.
1208 *
1209 * This function is called from thumb.php before Setup.php is included
1210 *
1211 * @param string $fname file name of the original image file
1212 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
1213 * @param boolean $shared (optional) use the shared upload directory
1214 * @access public
1215 */
1216 function wfImageThumbDir( $fname, $shared = false ) {
1217 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1218 if ( Image::isHashed( $shared ) ) {
1219 $dir = "$base/$fname";
1220
1221 if ( !is_dir( $base ) ) {
1222 $oldumask = umask(0);
1223 @mkdir( $base, 0777 );
1224 umask( $oldumask );
1225 }
1226
1227 if ( ! is_dir( $dir ) ) {
1228 $oldumask = umask(0);
1229 @mkdir( $dir, 0777 );
1230 umask( $oldumask );
1231 }
1232 } else {
1233 $dir = $base;
1234 }
1235
1236 return $dir;
1237 }
1238
1239 /**
1240 * Old thumbnail directory, kept for conversion
1241 */
1242 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1243 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1244 }
1245
1246 /**
1247 * Returns the image directory of an image's old version
1248 * If the directory does not exist, it is created.
1249 * The result is an absolute path.
1250 *
1251 * This function is called from thumb.php before Setup.php is included
1252 *
1253 * @param string $fname file name of the thumbnail file, including file size prefix
1254 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
1255 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
1256 * @access public
1257 */
1258 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1259 global $wgUploadDirectory, $wgHashedUploadDirectory,
1260 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1261 $dir = $shared ? $wgSharedUploadDirectory : $wgUploadDirectory;
1262 $hashdir = $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1263 if (!$hashdir) { return $dir.'/'.$subdir; }
1264 $hash = md5( $fname );
1265 $oldumask = umask(0);
1266
1267 # Suppress warning messages here; if the file itself can't
1268 # be written we'll worry about it then.
1269 wfSuppressWarnings();
1270
1271 $archive = $dir.'/'.$subdir;
1272 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1273 $archive .= '/' . $hash{0};
1274 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1275 $archive .= '/' . substr( $hash, 0, 2 );
1276 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1277
1278 wfRestoreWarnings();
1279 umask( $oldumask );
1280 return $archive;
1281 }
1282
1283
1284 /*
1285 * Return the hash path component of an image path (URL or filesystem),
1286 * e.g. "/3/3c/", or just "/" if hashing is not used.
1287 *
1288 * @param $dbkey The filesystem / database name of the file
1289 * @param $fromSharedDirectory Use the shared file repository? It may
1290 * use different hash settings from the local one.
1291 */
1292 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1293 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
1294 global $wgHashedUploadDirectory;
1295
1296 if( Image::isHashed( $fromSharedDirectory ) ) {
1297 $hash = md5($dbkey);
1298 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1299 } else {
1300 return '/';
1301 }
1302 }
1303
1304 /**
1305 * Returns the image URL of an image's old version
1306 *
1307 * @param string $fname file name of the image file
1308 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1309 * @access public
1310 */
1311 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1312 global $wgUploadPath, $wgHashedUploadDirectory;
1313
1314 if ($wgHashedUploadDirectory) {
1315 $hash = md5( substr( $name, 15) );
1316 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1317 substr( $hash, 0, 2 ) . '/'.$name;
1318 } else {
1319 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1320 }
1321 return wfUrlencode($url);
1322 }
1323
1324 /**
1325 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1326 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1327 *
1328 * @param string $length
1329 * @return int Length in pixels
1330 */
1331 function wfScaleSVGUnit( $length ) {
1332 static $unitLength = array(
1333 'px' => 1.0,
1334 'pt' => 1.25,
1335 'pc' => 15.0,
1336 'mm' => 3.543307,
1337 'cm' => 35.43307,
1338 'in' => 90.0,
1339 '' => 1.0, // "User units" pixels by default
1340 '%' => 2.0, // Fake it!
1341 );
1342 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1343 $length = FloatVal( $matches[1] );
1344 $unit = $matches[2];
1345 return round( $length * $unitLength[$unit] );
1346 } else {
1347 // Assume pixels
1348 return round( FloatVal( $length ) );
1349 }
1350 }
1351
1352 /**
1353 * Compatible with PHP getimagesize()
1354 * @todo support gzipped SVGZ
1355 * @todo check XML more carefully
1356 * @todo sensible defaults
1357 *
1358 * @param string $filename
1359 * @return array
1360 */
1361 function wfGetSVGsize( $filename ) {
1362 $width = 256;
1363 $height = 256;
1364
1365 // Read a chunk of the file
1366 $f = fopen( $filename, "rt" );
1367 if( !$f ) return false;
1368 $chunk = fread( $f, 4096 );
1369 fclose( $f );
1370
1371 // Uber-crappy hack! Run through a real XML parser.
1372 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1373 return false;
1374 }
1375 $tag = $matches[1];
1376 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1377 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1378 }
1379 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1380 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1381 }
1382
1383 return array( $width, $height, 'SVG',
1384 "width=\"$width\" height=\"$height\"" );
1385 }
1386
1387 /**
1388 * Is an image on the bad image list?
1389 */
1390 function wfIsBadImage( $name ) {
1391 global $wgLang;
1392
1393 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1394 foreach ( $lines as $line ) {
1395 if ( preg_match( '/^\*\s*\[\[:(' . $wgLang->getNsText( NS_IMAGE ) . ':.*(?=]]))\]\]/', $line, $m ) ) {
1396 $t = Title::newFromText( $m[1] );
1397 if ( $t->getDBkey() == $name ) {
1398 return true;
1399 }
1400 }
1401 }
1402 return false;
1403 }
1404
1405
1406
1407 /**
1408 * Wrapper class for thumbnail images
1409 * @package MediaWiki
1410 */
1411 class ThumbnailImage {
1412 /**
1413 * @param string $path Filesystem path to the thumb
1414 * @param string $url URL path to the thumb
1415 * @access private
1416 */
1417 function ThumbnailImage( $url, $width, $height, $path = false ) {
1418 $this->url = $url;
1419 $this->width = $width;
1420 $this->height = $height;
1421 $this->path = $path;
1422 }
1423
1424 /**
1425 * @return string The thumbnail URL
1426 */
1427 function getUrl() {
1428 return $this->url;
1429 }
1430
1431 /**
1432 * Return HTML <img ... /> tag for the thumbnail, will include
1433 * width and height attributes and a blank alt text (as required).
1434 *
1435 * You can set or override additional attributes by passing an
1436 * associative array of name => data pairs. The data will be escaped
1437 * for HTML output, so should be in plaintext.
1438 *
1439 * @param array $attribs
1440 * @return string
1441 * @access public
1442 */
1443 function toHtml( $attribs = array() ) {
1444 $attribs['src'] = $this->url;
1445 $attribs['width'] = $this->width;
1446 $attribs['height'] = $this->height;
1447 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1448
1449 $html = '<img ';
1450 foreach( $attribs as $name => $data ) {
1451 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';
1452 }
1453 $html .= '/>';
1454 return $html;
1455 }
1456
1457 }
1458 ?>